package com.example.webdemo.interceptor;

import com.example.webdemo.common.Common;
import com.example.webdemo.model.UserInfo;
import com.example.webdemo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zp
 * @version 1.0
 * @description: 登入拦截器
 * @date 2023/7/27 19:06
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private UserInfoService userInfoService;
    /**
     * 进入controller层之前拦截请求
     *
     * @param httpServletRequest
     * @param
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        String header = httpServletRequest.getHeader("Authorization");
        String method = httpServletRequest.getMethod();
        //处理预请求
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            return true;
        } else {
            if(header == null){
                response.setContentType("application/json; charset=utf-8");
                response.sendError(401,"无权访问");
            }else{
                UserInfo userInfo = userInfoService.selectByPhone(header);
                if(userInfo == null || userInfo.getToken()==null || !header.equals(userInfo.getToken())){
                    response.setContentType("application/json; charset=utf-8");
                    response.sendError(401,"无权访问");
                }else{
                    return true;
                }
            }
            return false;
        }
    }
}
